package com.sicau.filter;


import com.sicau.entity.dto.Composer;
import com.sicau.entity.dto.Manager;
import com.sicau.entity.pojo.vo.ResultVO;
import com.sicau.utils.JWT;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class TokenInterceptor implements HandlerInterceptor {

    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception arg3)
            throws Exception {
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView model) throws Exception {
    }

    //拦截每个请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("跨域请求设置");

        response.addHeader("Access-Control-Allow-Methods","*");
        response.addHeader("Access-Control-Allow-Origin","*");
//        response.addHeader("Access-Control-Max-Age","100");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type,token,Cookie");
//        //允许客户端发送cookies true表示接收，false不接受 默认为false？
        response.addHeader("Access-Control-Allow-Credentials","true");


        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("token");

        if(null != token){
            String requestURL = request.getRequestURL().toString();
            System.out.println(requestURL);
            if(requestURL.contains("user")){
                if(JWT.unsign(token, Composer.class) != null){
                    System.out.println(JWT.unsign(token, Composer.class));
                    return true;
                }
            }else if(requestURL.contains("manager")){
                if(JWT.unsign(token, Manager.class) != null){
                    System.out.println(JWT.unsign(token, Manager.class));
                    return true;
                }
            }

        }
        //重置response
//        response.reset();
       //设置编码格式
        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        responseMessage(response,writer);
        return false;
    }


    //请求不通过，返回错误信息给客户端
    private void responseMessage(HttpServletResponse response, PrintWriter out) {

        ResultVO resultVO = new ResultVO(-1, "没有权限");

        response.setHeader("Content-Type","application/json;charset=utf-8");

        JSONObject json = JSONObject.fromObject(resultVO);
        String jsonStr = json.toString();
        out.print(json);
        out.flush();
        out.close();
    }


}
